package com.cskaoyan.mall.search.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.search.dto.SearchRequest;
import com.cskaoyan.mall.search.dto.SearchResponse;
import com.cskaoyan.mall.search.form.SearchPageInfo;
import com.cskaoyan.mall.search.service.InitDataService;
import com.cskaoyan.mall.search.service.ProductSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Bowen Deng
 * @since 2022/07/16 11:00
 */
@RestController
@RequestMapping("/shopping")
public class SearchController {

    @Autowired
    InitDataService initDataService;

    @Autowired
    ProductSearchService productSearchService;

    @RequestMapping("search/init")
    public void esInit(){
        initDataService.initItems();
    }

    @GetMapping("search/{key}")
    public ResponseData searchKey(@PathVariable String key){
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.setKeyword(key);
        SearchResponse searchResponse = productSearchService.fuzzySearch(searchRequest);
        return new ResponseUtil<>().setData(searchResponse.getData());
    }

    @PostMapping("search")
    public ResponseData search(@RequestBody SearchPageInfo pageInfo){
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.setKeyword(pageInfo.getKey());
        searchRequest.setCurrentPage(pageInfo.getPage());
        searchRequest.setPageSize(pageInfo.getSize());
        searchRequest.setPriceGt(pageInfo.getPriceGt());
        searchRequest.setPriceLte(pageInfo.getPriceLte());
        searchRequest.setSort(pageInfo.getSort());

        SearchResponse searchResponse = productSearchService.search(searchRequest);
        return new ResponseUtil<>().setData(searchResponse);
    }
}
